package com.kaifamiao.kfm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaifamiao.kfm.entity.SysMenu;
import com.kaifamiao.kfm.entity.TreeMenuDTO;
import com.kaifamiao.kfm.service.SysMenuService;
import com.kaifamiao.kfm.mapper.SysMenuMapper;
import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author 10854
* @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
* @createDate 2022-08-21 15:22:43
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Override
    public List<SysMenu> findByRoleId(Long roleId) {
        return getBaseMapper().selectByRoleId(roleId);
    }


    @Override
    public List<TreeMenuDTO> treeMenu(Collection<SysMenu> collection){
        Iterator<SysMenu> iterator = collection.iterator();
        List<TreeMenuDTO> treeMenuDTOS = new ArrayList<>();

        Map<Long, TreeMenuDTO> map = new HashMap<>();
        while(iterator.hasNext()){
            SysMenu menu = iterator.next();
            if (menu.getParentId() == 0){ // 父级菜单
                map.put(menu.getMenuId(), new TreeMenuDTO(menu));
                iterator.remove();
            }
        }
        Iterator<SysMenu> iterator2 = collection.iterator();
        while(iterator2.hasNext()){
            SysMenu menu = iterator2.next();
            if (menu.getParentId() == 0){ // 父级菜单
                map.put(menu.getMenuId(), new TreeMenuDTO(menu));
            } else{
                TreeMenuDTO parent = map.get(menu.getParentId());
                if (parent != null){
                    parent.getChildren().add(menu);
                }
            }
            iterator2.remove();
        }

        treeMenuDTOS.addAll(map.values());

        for (TreeMenuDTO treeMenuDTO : treeMenuDTOS){
            treeMenuDTO.getChildren().sort((o1, o2) -> o1.getOrderNum() - o2.getOrderNum());
        }
        return treeMenuDTOS;
    }
}




